import 'package:flutter/foundation.dart';
import 'package:share_fit/app/controllers/base/base_controller.dart';
import 'package:share_fit/app/tools/log_utils.dart';
import 'package:share_fit/app/ute/uteped_const.dart';
import 'package:share_fit/app/ute/uteped_device.dart';

import 'hr_const.dart';
import 'hr_state.dart';

class HrLogic extends BaseController {
  final HrState state = HrState();

  void setHeartRateEnable(value) {
    state.isHeartRate.value = value;
    showLoading();
    bRemoteReqAsync(HrConst.setAutoHeartRate, {UTEPedConst.keyEnable: value})
        .then((success) => _onSetHeartRateEnable(success, value));
  }

  @override
  String getRemotePath() {
    return UTEPedConst.pathDeviceOptions;
  }

  @override
  String getStoragePath() {
    return UTEPedConst.pathDevice;
  }

  @override
  void initState() {
    state.isHeartRate.value =
        read(HrConst.isHeartRate, defaultValue: false);

    state.minHeartRate.value = read(HrConst.minHeartRate, defaultValue: 60);
    state.maxHeartRate.value = read(HrConst.maxHeartRate, defaultValue: 100);

    addStorageListener(HrConst.minHeartRate, (value) {
      state.minHeartRate.value = value;
    });
    addStorageListener(HrConst.maxHeartRate, (value) {
      state.maxHeartRate.value = value;
    });
  }

  void _onSetHeartRateEnable(success,value) {
    cancelLoading();
    if (success) {
      save(HrConst.isHeartRate, value);
    }
    else {
      state.isHeartRate.value = !value;
    }
    if (kDebugMode) {
      UTEPedDevice.instance.getDefaultConfiguration().then((value) => logger.d(value));
    }
  }

  @override
  void onRemoteEvent(event, method) {
    // empty
  }
}
